package no.uib.hplims.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;

/**
 * Class to enable downloading of files in Vaadin
 * See: https://vaadin.com/forum/-/message_boards/view_message/85012
 * 
 * @author John
 *
 */
public class FileDownloadResource extends FileResource {

	private static final long serialVersionUID = -4755625134415634509L;

	/**
	 * @param sourceFile The file to make available for download
	 * @param application The Vaadin application
	 */
	public FileDownloadResource(File sourceFile, Application application) {
		super(sourceFile, application);
	}

	/* (non-Javadoc)
	 * @see com.vaadin.terminal.FileResource#getStream()
	 */
	public DownloadStream getStream() {
		try {
			final DownloadStream ds = new DownloadStream(new FileInputStream(
					getSourceFile()), getMIMEType(), getFilename());
			ds.setParameter("Content-Disposition", "attachment; filename="
					+ getFilename());
			ds.setCacheTime(getCacheTime());
			return ds;
		} catch (final FileNotFoundException e) {
			// No logging for non-existing files at this level.
			return null;
		}
	}
}
